package com.louis.buddhist;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.louis.buddhist.data.C;
import com.louis.buddhist.data.entity.Book;
import com.louis.buddhist.data.entity.BookList;
import com.louis.buddhist.data.http.HttpManager;
import com.louis.buddhist.db.BookDaoOpen;
import com.louis.buddhist.ui.activity.ContactsUsActivity;
import com.louis.buddhist.ui.activity.DisclaimerActivity;
import com.louis.buddhist.ui.activity.ReadActivity;
import com.louis.buddhist.ui.adapter.ShelfAdapter;
import com.louis.buddhist.ui.base.BaseActivity;
import com.louis.buddhist.util.CommonUtil;
import com.louis.buddhist.util.WeakHandler;
import com.louis.buddhist.widget.dialog.CollectDialogFragment;
import com.louis.buddhist.widget.dialog.DownloadDialogFragment;
import com.louis.buddhist.widget.dialog.ReadDialogFragment;
import com.louis.buddhist.widget.view.DragGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.drawerlayout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.bookShelf)
    DragGridView bookShelf;
    @BindView(R.id.tv_constacts_us)
    TextView mTvConstactsUs;
    @BindView(R.id.tv_disclaimer)
    TextView mTvDisclaimer;
    @BindView(R.id.tv_collect)
    TextView mTvCollect;
    @BindView(R.id.tv_read)
    TextView mTvRead;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    @BindView(R.id.ll_layout)
    LinearLayout mLLLayout;
    @BindView(R.id.tv_main_page)
    TextView mTvMainPage;

    //
    private ShelfAdapter adapter;
    private List<BookList.EbookListBean> mBookList = new ArrayList<>();
    private Disposable mDisposable;
    private WeakHandler mWeakHandler = new WeakHandler();
    private SmartRefreshLayout refreshLayout;

    @Override
    protected int setContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        setSupportActionBar(mToolbar);
        //隐藏toolbar上的title
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
        //同步状态
        drawerToggle.syncState();
        //给侧滑控件设置监听
        mDrawerLayout.addDrawerListener(drawerToggle);
    }

    @Override
    protected void initData() {
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.requestDisallowInterceptTouchEvent(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                load();
            }
        });
        refreshLayout.autoRefresh();

        adapter = new ShelfAdapter(MainActivity.this, mBookList);
        bookShelf.setAdapter(adapter);
        bookShelf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mBookList.size() > position) {
                    BookList.EbookListBean bookList = mBookList.get(position);
                    Book book = BookDaoOpen.queryByName(MainActivity.this, bookList.getTitle());
                    if (book == null) {
                        downloadBook(bookList);
                    } else {
                        toReadBook(book);
                    }
                }
            }
        });

        mTvConstactsUs.setOnClickListener(this);
        mTvDisclaimer.setOnClickListener(this);
        mTvCollect.setOnClickListener(this);
        mTvRead.setOnClickListener(this);
        mLLLayout.setOnClickListener(this);
        mTvMainPage.setOnClickListener(this);

        mTvVersion.setText("版本號：" + CommonUtil.getVersion(this));
    }

    private void load() {
        mBookList.clear();
        if (CommonUtil.isNetworkAvailable(this)) {
            getData();
        } else {
            List<Book> books = BookDaoOpen.queryAll(this);

            List<BookList.EbookListBean> ebook_list = new ArrayList<>();
            for (int i = 0; i < books.size(); i++) {
                Book book = books.get(i);
                BookList.EbookListBean bean = new BookList.EbookListBean();
                bean.setId(book.getId() + "");
                bean.setCover(book.getCover());
                bean.setContent_zip(book.getPath());
                bean.setTitle(book.getName());
                ebook_list.add(bean);
            }
            mBookList.addAll(ebook_list);
            adapter.setBookList(mBookList);
        }
        refreshLayout.finishRefresh();
    }

    private void toReadBook(Book book) {
        Intent intent = new Intent(this, ReadActivity.class);
        intent.putExtra(C.IntentKey.MESSAGE_INTENT_KEY, book);
        startActivity(intent);
    }

    private void getData() {

        HttpManager.getApiInstance().getBookList()
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //                        LoadingDialog.make(MainActivity.this).show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        //                        LoadingDialog.cancel();
                    }
                })
                .subscribe(new Observer<BookList>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(BookList entity) {
                        List<BookList.EbookListBean> ebook_list = entity.getEbook_list();
                        mBookList.addAll(ebook_list);
                        adapter.setBookList(mBookList);
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onComplete() {
                        System.out.println("onComplete");
                    }
                });
    }

    private void downloadBook(BookList.EbookListBean entity) {
        DownloadDialogFragment fragment = new DownloadDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString(C.IntentKey.MESSAGE_INTENT_KEY, entity.getTitle());
        bundle.putString(C.IntentKey.MESSAGE_INTENT_KEY2, entity.getContent_zip());
        bundle.putString(C.IntentKey.MESSAGE_INTENT_KEY3, entity.getCover());
        bundle.putString(C.IntentKey.MESSAGE_INTENT_KEY4, entity.getId() + "");
        fragment.setArguments(bundle);
        fragment.show(getSupportFragmentManager(), "DownloadDialogFragment");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        mWeakHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_constacts_us:
                toContacts();
                break;
            case R.id.tv_disclaimer:
                toDisclaimer();
                break;
            case R.id.tv_collect:
                showCollectList();
                break;
            case R.id.tv_read:
                showReadList();
                break;
            case R.id.tv_main_page:
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                break;
        }
    }

    private void toContacts() {
        Intent intent = new Intent(this, ContactsUsActivity.class);
        startActivity(intent);
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void toDisclaimer() {
        Intent intent = new Intent(this, DisclaimerActivity.class);
        startActivity(intent);
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void showCollectList() {
        CollectDialogFragment fragment = new CollectDialogFragment();
        fragment.show(getSupportFragmentManager(), "CollectDialogFragment");
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void showReadList() {
        ReadDialogFragment fragment = new ReadDialogFragment();
        fragment.show(getSupportFragmentManager(), "ReadDialogFragment");
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }
}
